#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "atomsem.h"


uint8_t atomSemCreate(ATOM_SEM *sem, uint8_t initial_count)
{
    sem->save_ptr = (POINTER)xSemaphoreCreateCounting(255, initial_count);
    if (sem->save_ptr != NULL) {
        return ATOM_OK;
    }
    return ATOM_ERROR;
}

uint8_t atomSemDelete(ATOM_SEM *sem)
{
    if (xSemaphoreTake(sem->save_ptr, portMAX_DELAY) == pdTRUE) {
        vSemaphoreDelete(sem->save_ptr);
        return ATOM_OK;
    }
    return ATOM_ERROR;
}

uint8_t atomSemGet(ATOM_SEM *sem, int32_t timeout)
{
    if (timeout < 0) {
        return xSemaphoreTake(sem->save_ptr, portMAX_DELAY) == pdTRUE ? ATOM_OK : ATOM_ERROR;
    } else {
        TickType_t ticks = pdMS_TO_TICKS(timeout);
        return xSemaphoreTake(sem->save_ptr, ticks) == pdTRUE ? ATOM_OK : ATOM_ERROR;
    }
}

uint8_t atomSemPut(ATOM_SEM *sem)
{
    return xSemaphoreGive(sem->save_ptr) == pdTRUE ? ATOM_OK : ATOM_ERROR;
}

uint8_t atomSemResetCount(ATOM_SEM *sem, uint8_t count)
{
    while (count > 0) {
        xSemaphoreGive(sem->save_ptr);
        count--;
    }
    return ATOM_OK;
}